﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ArgusPCLib.Mathematics.Reflection;

namespace ArgusPCLib.Mathematics
{
	public static class Algorithms
	{
		public static T Bisection<T>(Interval<T> interval, Func<T, int> func, T terminationRange)
			where T : ILinearScalar
		{
			T two = (T)ScalarReflector<T>.One.Add(ScalarReflector<T>.One);
			T RetVal = (T)interval.LowerLimit.Add(interval.UpperLimit).Divide(two);

			while (interval.Range.IsGreaterThan(terminationRange))
			{
				int compare = func(RetVal);
				if (compare == 0)
					return RetVal;
				else if (compare < 0)
					interval = new Interval<T>(RetVal, interval.UpperLimit);
				else
					interval = new Interval<T>(interval.LowerLimit, RetVal);

				RetVal = (T)interval.LowerLimit.Add(interval.UpperLimit).Divide(two);
			}
			return RetVal;
		}
	}
}
